package com.castle.fortress.admin.form.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.castle.fortress.admin.form.dto.ColModelDto;
import com.castle.fortress.admin.form.dto.FormConfigDto;
import com.castle.fortress.admin.form.dto.FormModelDto;
import com.castle.fortress.admin.form.entity.FormConfigEntity;
import com.castle.fortress.admin.form.mapper.FormConfigMapper;
import com.castle.fortress.admin.form.service.FormConfigService;
import com.castle.fortress.admin.utils.BizCommonUtil;
import com.castle.fortress.common.exception.BizException;
import com.castle.fortress.common.respcode.BizErrorCode;
import com.castle.fortress.common.respcode.GlobalRespCode;
import com.castle.fortress.common.utils.CommonUtil;
import com.castle.fortress.common.utils.ConvertUtil;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 表单配置管理 服务实现类
 *
 * @author castle
 * @since 2021-11-10
 */
@Service
public class FormConfigServiceImpl extends ServiceImpl<FormConfigMapper, FormConfigEntity> implements FormConfigService {
    /**
    * 获取查询条件
    * @param formConfigDto
    * @return
    */
    public QueryWrapper<FormConfigEntity> getWrapper(FormConfigDto formConfigDto){
        QueryWrapper<FormConfigEntity> wrapper= new QueryWrapper();
        if(formConfigDto != null){
            FormConfigEntity formConfigEntity = ConvertUtil.transformObj(formConfigDto,FormConfigEntity.class);
            wrapper.like(StrUtil.isNotEmpty(formConfigEntity.getName()),"name",formConfigEntity.getName());
            wrapper.eq(formConfigEntity.getStatus() != null,"status",formConfigEntity.getStatus());
            wrapper.orderByDesc("create_time");
        }
        return wrapper;
    }


    @Override
    public IPage<FormConfigDto> pageFormConfig(Page<FormConfigDto> page, FormConfigDto formConfigDto) {
        QueryWrapper<FormConfigEntity> wrapper = getWrapper(formConfigDto);
        Page<FormConfigEntity> pageEntity = new Page(page.getCurrent(), page.getSize());
        Page<FormConfigEntity> formConfigPage=baseMapper.selectPage(pageEntity,wrapper);
        Page<FormConfigDto> pageDto = new Page(formConfigPage.getCurrent(), formConfigPage.getSize(),formConfigPage.getTotal());
        pageDto.setRecords(ConvertUtil.transformObjList(formConfigPage.getRecords(),FormConfigDto.class));
        return pageDto;
    }

    @Override
    public IPage<FormConfigDto> pageFormConfigExtends(Page<FormConfigDto> page, FormConfigDto formConfigDto){
        Map<String,Long> pageMap = BizCommonUtil.getPageParam(page);
        FormConfigEntity formConfigEntity = ConvertUtil.transformObj(formConfigDto,FormConfigEntity.class);
        List<FormConfigEntity> formConfigList=baseMapper.extendsList(pageMap,formConfigEntity);
        Long total = baseMapper.extendsCount(formConfigEntity);
        Page<FormConfigDto> pageDto = new Page(page.getCurrent(), page.getSize(),total);
        pageDto.setRecords(ConvertUtil.transformObjList(formConfigList,FormConfigDto.class));
        return pageDto;
    }
    @Override
    public FormConfigDto getByIdExtends(Long id){
        FormConfigEntity  formConfigEntity = baseMapper.getByIdExtends(id);
        return ConvertUtil.transformObj(formConfigEntity,FormConfigDto.class);
    }

    @Override
    public List<FormConfigDto> listFormConfig(FormConfigDto formConfigDto){
        QueryWrapper<FormConfigEntity> wrapper = getWrapper(formConfigDto);
        List<FormConfigEntity> list = baseMapper.selectList(wrapper);
        return ConvertUtil.transformObjList(list,FormConfigDto.class);
    }

    @Override
    public FormModelDto convertToModel(FormConfigEntity formConfigEntity) {
        FormModelDto modelDto=new FormModelDto();
        if(CommonUtil.verifyParamNull(formConfigEntity,formConfigEntity.getId(),formConfigEntity.getTbContent())){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        List<ColModelDto> cols=new ArrayList<>();
        JSONArray jsonArray=new JSONArray(formConfigEntity.getTbContent());
        if(jsonArray.size()<1){
            throw new BizException(BizErrorCode.FORM_COL_EMPTY_ERROR);
        }
        modelDto.setTbName("castle_form"+formConfigEntity.getId());
        String tag="",type="varchar(100)",label="";
        for(int i=0;i<jsonArray.size();i++){
            ColModelDto col=new ColModelDto();
            JSONObject o=jsonArray.getJSONObject(i);
            col.setColName(o.getStr("__vModel__"));
            tag=o.getJSONObject("__config__").getStr("tag");
            col.setColTag(tag);
            //分割组件不沉淀数据库
            if("el-divider".equals(tag)||"span".equals(tag)){
                continue;
            }
            switch (tag){
                case "el-input": type="varchar(100)";break;
                case "el-input-number": type="varchar(9)";break;
                case "tinymce": type="longtext";break;
                case "fortress-editor": type="longtext";break;
                case "el-select": type="varchar(100)";break;
                case "el-cascader": type="varchar(100)";break;
                case "el-radio-group": type="varchar(100)";break;
                case "el-checkbox-group": type="varchar(100)";break;
                case "el-switch": type="tinyint(1)";break;
                case "el-slider": type="varchar(100)";break;
                case "el-time-picker": type="varchar(20)";break;
                case "el-date-picker": type="varchar(50)";break;
                case "el-rate": type="varchar(2)";break;
                case "el-color-picker": type="varchar(16)";break;
                case "el-upload": type="text";break;
                case "image-upload": type="text";break;
                case "file-upload": type="text";break;
                case "video-upload": type="text";break;
                case "v-auditer": type="text";break;
                case "fortress-region":type = "varchar(100)";break;
                case "create_user":type = "bigint(64)";break;
                case "create_time":type = "datetime";break;
            }
            col.setColType(type);
            label=o.getJSONObject("__config__").getStr("label");
            col.setColComment(label);
            cols.add(col);
            //省市区组件
            if("fortress-region".equals(tag)){
                ColModelDto colName=new ColModelDto();
                colName.setColName(col.getColName()+"Name");
                colName.setColType("varchar(150)");
                colName.setColComment(col.getColComment()+"名称描述");
                colName.setColTag("fortress-region-desc");
                cols.add(colName);
            }
        }
        modelDto.setCols(cols);
        return modelDto;
    }

    @Override
    public boolean updateIpById(FormConfigEntity formConfigEntity) {
        return baseMapper.updateIpById(formConfigEntity)>0;
    }

}

